package com.coding.basic.stack.expr;

import java.util.List;
import java.util.Stack;

public class PostfixExpr {
    String expr = null;

    public PostfixExpr(String expr) {
        this.expr = expr;
    }

    public float evaluate() {
        if (expr == null) {
            throw new NullPointerException("expr can't be null");
        }

        TokenParser tokenParser = new TokenParser();
        List<Token> tokenList = tokenParser.parse(expr);

        Stack<Float> numStack = new Stack<>();
        for (Token token : tokenList) {
            if (token.isNumber()) {
                numStack.push((float) token.getIntValue());
            } else if (token.isOperator()) {
                float f2 = numStack.pop();
                float f1 = numStack.pop();
                Float result = calculate(token.toString(), f1, f2);
                numStack.push(result);
            }
        }
        return numStack.pop();
    }

    private Float calculate(String op, Float f1, Float f2) {
        if (op.equals("+")) {
            return f1 + f2;
        }
        if (op.equals("-")) {
            return f1 - f2;
        }
        if (op.equals("*")) {
            return f1 * f2;
        }
        if (op.equals("/")) {
            return f1 / f2;
        }
        throw new RuntimeException(op + " is not supported");
    }
}